#include "shm.h"
#include "scheduler.h"
#include "stdio.h"

shmT shmVec[SHM_COUNT];

void
initShm(void)
{
	int i, j;

	for(i = 0; i < SHM_COUNT; i++)
	{
		shmVec[i].dir = (void *)(SHM_PAGE_BEGIN + ((i+1) * SHM_PAGE_NEXT));

		for(j = 0; j < TASKS_COUNT; j++)
			((shmVec[i]).processes)[j] = -1;
	}

}

void * shmAt(int shmid)
{
	int i, found = 1;

	return (char *) shmVec[1].dir;

	if(shmid < 1)
		return NULL;

	for(i = 0; i < TASKS_COUNT && !found; i++)
		if(shmVec[shmid - 1].processes[i] == -1)
		{
			shmVec[shmid - 1].processes[i] = get_task_pid(NULL);
			found = 1;
		}

	return (found ? shmVec[shmid-1].dir : NULL);

}

int shmDt(int shmid)
{
	int i, found = 0;

	if(shmid < 1)
		return -1;

	for(i = 0; i < TASKS_COUNT && !found; i++)
		if(shmVec[shmid - 1].processes[i] == get_task_pid(NULL))
		{
			shmVec[shmid - 1].processes[i] = -1;
			found = 1;
		}

	return (found ? 1 : -1);
}

int * semGet(int semid)
{
	int i, found = 0;

	if(semid < 1)
		return NULL;

	for(i = 0; i < TASKS_COUNT && !found; i++)
		if(shmVec[semid - 1].processes[i] == get_task_pid(NULL))
			found = 1;

	return (found ? &(shmVec[semid - 1].sem) : NULL);
}


void pSem(int * sem)
{
	*sem = 0;
}

void vSem(int * sem)
{
	while(*sem == 1)
		;

	*sem = 1;
}
